#include "case.h"

#include <QPainter>
#include <QMouseEvent>
#include <QDebug>
#include <QRandomGenerator>
#include <QDesktopWidget>
#include <QApplication>

Case::Case(QWidget *parent) : QWidget(parent)
{
    _pixmap.load(":/img/pic1");

    setFixedSize(_pixmap.size());
    startTimer(100); // 每隔100hm调用一次timerEvent
}

void Case::paintEvent(QPaintEvent *ev)
{
    QPainter p(this);
    p.drawPixmap(rect(), _pixmap);
}

void Case::timerEvent(QTimerEvent *ev)
{
    flutter(); // 默认参数(10, 30)
}

void Case::mousePressEvent(QMouseEvent *ev)
{
    if(ev->button() == Qt::LeftButton) // 鼠标左键
    {
        _point = ev->globalPos() - this->geometry().topLeft();
        qDebug() << "mpe 执行";
    }
}

void Case::mouseMoveEvent(QMouseEvent *ev)
{
    if(ev->buttons() & Qt::LeftButton) // 判断左键是否参与移动，按下时为"0001"
    {
        this->move(ev->globalPos() - _point);
        qDebug() << "mme 执行";
    }
}

void Case::enterEvent(QEvent *ev)
{
    flutter(-100, 100);
}

void Case::flutter(int min, int max)
{
    _index++;
    if(_index > 2)
        _index = 1;

    // _index 循环1,2
    // 以此进行图片的循环切换
    QString name = QString(":/img/pic%1").arg(_index);
    _pixmap.load(name);
    update();

    int stepX = QRandomGenerator::global()->bounded(min, max); // 每次移动步长
    int stepY = QRandomGenerator::global()->bounded(min, max);

    int curX = this->geometry().topLeft().x() + stepX;
    int curY = this->geometry().topRight().y() + stepY;

    QDesktopWidget *desk = QApplication::desktop();
    if(curX >= desk->screenGeometry().right()) // curX超出屏幕右边界，重置回左边界
    {
        curX = desk->screenGeometry().left();
    }

    if(curY >= desk->screenGeometry().bottom()) // curY超出屏幕下边界，重置回上边界
    {
        curY = desk->screenGeometry().top();
    }

    move(curX, curY); // 移动图标
}
